package com.data2wisdom.comm.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Base64;

public class Base64Utils {
	/**
	 * BASE64解密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptBASE64(String key) throws Exception {
		byte[] base64decodedBytes = Base64.getDecoder().decode(key);
		return new String(base64decodedBytes);
	}

	/**
	 * BASE64加密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptBASE64(byte[] key) throws Exception {
		String base64encodedString = Base64.getEncoder().encodeToString(key);
		return base64encodedString;
	}

	public static void writeString(String fileName, String content) throws Exception {
		File file = new File(fileName);
		Writer out = new FileWriter(file);
		out.write(content);
		out.close();
	}

	public static String readString(String fileName) throws Exception{
            //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流，请考虑使用 FileReader。 
            FileInputStream inStream = new FileInputStream(fileName);
 
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
            byte[] buffer=new byte[1024];
 
            int length=-1;
 
            while((length = inStream.read(buffer)) != -1)
 
            {
                bos.write(buffer,0,length);
            }
            bos.close();
 
            inStream.close();
            return bos.toString();   
	}
}
